<template>
  <a-drawer
    v-model:visible="visible"
    title="协议详细信息"
    placement="right"
    :width="800"
    :closable="true"
    :mask-closable="true"
    @close="handleClose"
  >
    <template #extra>
      <a-space>
        <a-button v-if="protocol" type="primary" size="small" @click="exportProtocol">
          导出协议
        </a-button>
        <a-button type="default" size="small" @click="handleClose">
          关闭
        </a-button>
      </a-space>
    </template>

    <ProtocolInfoDisplay
      :protocol="protocol"
      :is-default="isDefault"
    />
  </a-drawer>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { message } from 'ant-design-vue'
import ProtocolInfoDisplay from './ProtocolInfoDisplay.vue'
import type { AnyProtocol } from '../types/channel-config-protocol'

// Props
interface Props {
  protocol?: AnyProtocol | null
  isDefault?: boolean
  visible?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  protocol: null,
  isDefault: false,
  visible: false
})

// Emits
const emit = defineEmits<{
  'update:visible': [visible: boolean]
  close: []
}>()

// 内部状态
const visible = ref(props.visible)

// 监听外部 visible 变化
watch(() => props.visible, (newVisible) => {
  visible.value = newVisible
})

// 监听内部 visible 变化，同步到外部
watch(visible, (newVisible) => {
  emit('update:visible', newVisible)
})

// 关闭处理
const handleClose = () => {
  visible.value = false
  emit('close')
}

// 导出协议信息
const exportProtocol = () => {
  if (!props.protocol) return

  try {
    const exportData = {
      protocolId: props.protocol.protocolId,
      protocolType: props.protocol.protocolType,
      name: props.protocol.name,
      version: props.protocol.version,
      description: props.protocol.description,
      configFields: props.protocol.configFields,
      defaultValues: props.protocol.defaultValues,
      uiConfig: props.protocol.uiConfig,
      metadata: props.protocol.metadata,
      isDefault: props.isDefault,
      exportTime: new Date().toISOString()
    }

    const jsonString = JSON.stringify(exportData, null, 2)

    // 创建下载链接
    const blob = new Blob([jsonString], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `protocol-${props.protocol.protocolId}-${new Date().toISOString().split('T')[0]}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    message.success('协议信息导出成功')
  } catch (error) {
    message.error('导出失败：' + (error as Error).message)
  }
}

// 暴露方法供外部调用
defineExpose({
  open: () => {
    visible.value = true
  },
  close: () => {
    visible.value = false
  }
})
</script>

<style scoped>
/* 可以添加一些自定义样式 */
:deep(.ant-drawer-body) {
  padding: 16px;
}

:deep(.ant-drawer-header) {
  border-bottom: 1px solid #f0f0f0;
}
</style>